<template>
  <div class="form-image-select">
    <div class="upload">
      <el-input v-if="!onlyButton" v-model="filesStr" class="input" placeholder="请输入内容" @input="filesStrChange" />
      <el-button class="btn-upload" type="primary">
        <input
          ref="fileInput"
          class="upload-input"
          type="file"
          :multiple="multi"
          :accept="accept"
          @change="fileChange"
        >
        {{ uploadBtnText }}
      </el-button>
<!--      <el-button v-if="showSelect" type="success" @click="showSelectAttachment = true">{{ chooseBtnText }}</el-button>-->
      <!--      <el-button type="warning">选择</el-button>-->
    </div>
    <div v-if="!onlyButton" class="preview-list">
      <template v-if="multi">
        <template v-if="files && files.length">
          <draggable
            class="flex-row flex-wrap"
            :list="files"
            v-bind="$attrs"
            :options="{animation:500}"
          >
            <div v-for="(item, index) in files" :key="index" class="preview-item">
              <a :href="item | fileServer" target="_blank">
                <img class="preview-img" :src="item | fileServer">
                <div class="del-item" @click.stop.prevent="handleDelete(index)">删除</div>
              </a>
            </div>
          </draggable>
        </template>
      </template>
      <template v-else>
        <div v-if="files" class="preview-item">
          <a :href="files" target="_blank">
            <img class="preview-img" :src="files | fileServer">
            <div class="del-item" @click.stop.prevent="handleSingleDelete">删除</div>
          </a>
        </div>
      </template>
    </div>
    <el-dialog v-if="showSelect" title="选择文件" :modal="false" :visible.sync="showSelectAttachment" width="80%" style="max-width: 1800px;">
<!--      <Attachment :select="showSelect" :show.sync="showSelectAttachment" @change="selectAttachment" />-->
    </el-dialog>
  </div>
</template>
<script>
import { upload } from '@/api/upload'
import excelImage from '@/assets/images/fileType/excel.png'
import fileImage from '@/assets/images/fileType/file.png'
import videoImage from '@/assets/images/fileType/video.png'
import wordImage from '@/assets/images/fileType/word.png'
// import Attachment from '@/views/shop/attachment/list'
import draggable from 'vuedraggable'
export default {
  components: { /*Attachment,*/ draggable },
  filters: {
    fileTypes(val) {
      // if (!/\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test(ths.value)) {
      //   alert("图片类型必须是.gif,jpeg,jpg,png中的一种");
      //   ths.value = "";
      //   return false;
      // }
      console.log(val)
      if (/\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test(val.toUpperCase())) {
        return val
      } else if (/\.(DOC|DOCX)$/.test(val.toUpperCase())) {
        return wordImage
      } else if (/\.(XLS|XLSX|CSV)$/.test(val.toUpperCase())) {
        return excelImage
      } else if (/\.(MP4|AVI)$/.test(val.toUpperCase())) {
        return videoImage
      } else {
        return fileImage
      }
    }
  },
  props: {
    onlyButton: {
      type: Boolean,
      default() {
        return false
      }
    },
    showSelect: {
      type: Boolean,
      default() {
        return false
      }
    },
    unsave: {
      type: Boolean,
      default() {
        return false
      }
    },
    files: {
      default() {
        return null
      }
    },
    accept: {},
    multi: {
      type: Boolean,
      default() {
        return false
      }
    },
    uploadBtnText: {
      type: String,
      default() {
        return '上传'
      }
    },
    chooseBtnText: {
      type: String,
      default() {
        return '选择'
      }
    }
    // value: {}
  },
  data() {
    return {
      filesStr: '',
      showSelectAttachment: false
    }
  },
  watch: {
    files: {
      handler: function(val, oldVal) {
        if (this.multi) {
          if (!this.isArray(val)) {
            if (!val) {
              this.$emit('update:files', [])
            } else {
              this.$emit('update:files', [val])
            }
            return
          }
          this.filesStr = val ? val.join(',') : ''
        } else {
          this.filesStr = val ? `${val}` : ''
        }
      },
      immediate: true
    }
  },
  methods: {
    selectAttachment(row) {
      if (this.multi) {
        this.$emit('update:files', this.files ? [...this.files, row.fullurl] : [])
      } else {
        this.$emit('update:files', row.fullurl)
      }
      this.$refs.fileInput.value = ''
    },
    isArray(arg) {
      if (typeof Array.isArray === 'undefined') {
        return Object.prototype.toString.call(arg) === '[object Array]'
      }
      return Array.isArray(arg)
    },
    handleDelete(index) {
      const temp = [...this.files]
      temp.splice(index, 1)
      this.$emit('update:files', temp)
    },
    handleSingleDelete() {
      this.$emit('update:files', null)
    },
    filesStrChange(fileStr) {
      if (this.multi) {
        this.$emit('update:files', fileStr.split(','))
      } else {
        this.$emit('update:files', fileStr)
      }
    },
    fileChange(e) {
      const files = e.target.files
      for (let i = 0; i < files.length; i++) {
        if (this.quillImgBefore(files[i])) {
          const data = new FormData()
          data.append('file', files[i])
          data.append('unsave', this.unsave)
          upload(data).then(res => {
            if (this.multi) {
              this.$emit('update:files', this.files ? [...this.files, res.data.url] : [])
            } else {
              this.$emit('update:files', res.data.url)
            }
            this.$refs.fileInput.value = ''
          })
        }
      }
    },
    // 富文本图片上传前
    quillImgBefore(file) {
      const fileType = file.type
      console.log(fileType)
      // if (fileType === 'image/jpeg' || fileType === 'image/png') {
      //   return true
      // } else {
      //   this.$message.error('请插入图片类型文件(jpg/jpeg/png)')
      //   return false
      // }
      return true
    }
  }
}
</script>
<style lang="scss" scoped>
.form-image-select {
  .upload {
    display: flex;
    flex-direction: row;

    .input {
      flex: 1;
    }

    .btn-upload {
      margin-left: 10px;
      position: relative;

      .upload-input {
        position: absolute;
        width: 100%;
        height: 100%;
        left: 0;
        top: 0;
        opacity: 0;
        cursor: pointer;
      }
    }
  }

  .preview-list {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;

    .preview-item {
      margin-top: 6px;
      margin-right: 10px;
      position: relative;
      height: 100px;
      border: 1px #999 solid;
      border-radius: 4px;
      overflow: hidden;

      .preview-img {
        display: block;
        height: 100px;
      }

      &:hover {
        .del-item {
          display: block;
        }
      }

      .del-item {
        display: none;
        position: absolute;
        bottom: 0;
        left: 0;
        width: 100%;
        font-size: 12px;
        line-height: 24px;
        text-align: center;
        background: rgba(255, 0, 0, .8);
        color: #fff;
        cursor: pointer;
        user-select: none;

        &:hover {
          background: rgba(255, 0, 0, .7);
        }

        &:active {
          background: rgba(255, 0, 0, .85);
        }
      }
    }
  }

}
</style>
